package com.zeei.bfs.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zeei.bfs.dao.DeptinfoDao;
import com.zeei.bfs.dao.RoleDao;
import com.zeei.bfs.dao.UserDao;
import com.zeei.bfs.dao.UserRoleDao;
import com.zeei.bfs.service.DeptinfoService;
import com.zeei.bfs.service.RoleService;
import com.zeei.bfs.vo.DeptinfoVO;
import com.zeei.bfs.vo.OrgTreeVO;
import com.zeei.bfs.vo.QueryDeptParamVO;
import com.zeei.bfs.vo.RoleVO;
import com.zeei.bfs.vo.UserRoleVO;
import com.zeei.common.constant.GlobalConstant;
import com.zeei.common.utils.SessionInfoUtil;
import com.zeei.common.utils.TreeUtil;
import com.zeei.common.vo.TreeNodeVO;
import com.zeei.common.vo.UserVO;

@Service("deptinfoService")
public class DeptinfoServiceImpl extends BasicServiceImpl implements DeptinfoService {

	@Autowired
	private DeptinfoDao deptinfoDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private UserRoleDao userRoleDao;

	@Autowired
	private RoleDao roleDao;

	@Autowired
	private RoleService roleService;

	@Override
	public List<TreeNodeVO<DeptinfoVO>> queryDeptinfo(QueryDeptParamVO queryDeptParam, UserVO user) {
		Map<String, Object> condition = queryDeptParam.convertConditionMap();
		List<DeptinfoVO> list = deptinfoDao.queryDeptinfoByCondition(condition);
		String deptId = getDeptId();
		List<TreeNodeVO<DeptinfoVO>> resultList = new ArrayList<TreeNodeVO<DeptinfoVO>>();
		if (StringUtils.isNotEmpty(queryDeptParam.getSearchDeptName())) {
			List<DeptinfoVO> allList = deptinfoDao.queryDeptinfoByCondition(new HashMap<String, Object>());
			List<TreeNodeVO<DeptinfoVO>> treeList = TreeUtil.buildSearchNodeTree(allList, list);
			resultList = treeList;
		} else {
			resultList = TreeUtil.buildTreeNodeTree(list, deptId);
			// TreeUtil.setInitCloseState(resultList);
		}
		return resultList;
	}

	@Override
	public boolean addDeptinfo(DeptinfoVO deptinfo) {

		Integer count = deptinfoDao.insertDeptinfo(deptinfo);

		return count > 0;
	}

	@Override
	public boolean editDept(DeptinfoVO deptinfo) {
		if (deptinfo == null || deptinfo.getDeptId() == null) {
			return GlobalConstant.FAILED;
		}
		// 修改当前部门数据
		Integer count = deptinfoDao.updateDeptinfoById(deptinfo);

		return count > 0;
	}

	@Override
	public boolean dropDept(List<String> list) {
		if (CollectionUtils.isEmpty(list)) {
			return true;
		}

		List<String> allDeptId = list;

		// 1)删除用户的关联关系
		userDao.removeRelationByDeptIds(allDeptId);

		// 2)删除部门拥有的角色
		Map<String, Object> roleMap = new HashMap<String, Object>();
		roleMap.put("deptIdList", allDeptId);
		List<RoleVO> rolelist = roleDao.queryRoleByCondition(roleMap);
		// roleDao.deleteRoleByDeptIds(list);
		if (CollectionUtils.isNotEmpty(rolelist)) {
			List<Integer> roleIdList = new ArrayList<Integer>(rolelist.size());
			for (RoleVO role : rolelist) {
				roleIdList.add(role.getRoleId());
			}
			// 删除角色用户关联关系
			// userRoleDao.deleteUserRoleByRoleIdList(roleIdList);
			// 删除角色
			roleService.dropRole(roleIdList);
		}
		// 3)删除部门及其子节点

		Integer count = deptinfoDao.deleteDeptByIds(allDeptId);
		return count > 0;
	}

	@Override
	public boolean validDeptName(DeptinfoVO deptinfo) {
		if (deptinfo == null || StringUtils.isEmpty(deptinfo.getDeptName())) {
			return GlobalConstant.FAILED;// 失败
		}
		if (deptinfo.getDeptId() != null) {
			DeptinfoVO queryVO = new DeptinfoVO();
			queryVO.setDeptId(deptinfo.getDeptId());
			List<DeptinfoVO> oldList = deptinfoDao.queryDeptinfo(queryVO);
			if (CollectionUtils.isNotEmpty(oldList) && //
					deptinfo.getDeptName().equals(oldList.get(0).getDeptName())) {
				return GlobalConstant.SUCCEED;// 成功
			}
		}
		DeptinfoVO queryVO = new DeptinfoVO();
		queryVO.setDeptName(deptinfo.getDeptName());
		List<DeptinfoVO> deptList = deptinfoDao.queryDeptinfo(queryVO);
		if (CollectionUtils.isNotEmpty(deptList)) {
			return GlobalConstant.FAILED;// 失败
		}
		return GlobalConstant.SUCCEED;// 成功
	}

	@Override
	public List<TreeNodeVO<DeptinfoVO>> queryDeptinfo(DeptinfoVO deptinfo) {
		List<DeptinfoVO> list = deptinfoDao.queryDeptinfo(deptinfo);
		String deptId = getDeptId();
		return TreeUtil.buildTreeNodeTree(list, deptId);
	}

	@Override
	public List<TreeNodeVO<OrgTreeVO>> queryDeptuserTreeList(Integer roleId) {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("roleId", roleId);
		List<OrgTreeVO> list = deptinfoDao.queryDeptuserTreeList(condition);
		String id = generatIdByDeptId(getDeptId());
		return TreeUtil.buildTreeNodeTree(list, id);
	}

	/**
	 * 方法描述:生成id,通过部门ID
	 *
	 * @param deptId
	 * @return
	 */
	private static String generatIdByDeptId(String deptId) {
		if (deptId == null) {
			return null;
		}
		return "d" + deptId;
	}

	@Override
	public boolean addDeptuserRelation(Integer createId, Integer roleId, String[] ids) {
		List<Integer> userIdList = new ArrayList<Integer>();
		for (int i = 0; i < ids.length; i++) {
			if (isUser(ids[i])) {
				String realId = ids[i].substring(1);
				userIdList.add(Integer.parseInt(realId));
			}
		}
		// 1)查询角色有的用户
		UserRoleVO queryBean = new UserRoleVO();
		queryBean.setRoleId(roleId);
		List<UserRoleVO> userRoleList = userRoleDao.queryUserRole(queryBean);
		// 2)匹配
		Map<Integer, UserRoleVO> userRoleMap = new HashMap<Integer, UserRoleVO>(userRoleList.size());
		for (UserRoleVO vo : userRoleList) {
			userRoleMap.put(vo.getUserId(), vo);
		}

		List<Integer> deleteList = new ArrayList<Integer>();
		List<UserRoleVO> insertList = new ArrayList<UserRoleVO>();

		Map<Integer, Integer> map = new HashMap<Integer, Integer>(userIdList.size());
		// 如果传递的数据在存储的数据中没找到，增加
		for (Integer userId : userIdList) {
			UserRoleVO userRole = userRoleMap.get(userId);
			if (userRole == null) {
				UserRoleVO vo = new UserRoleVO();
				vo.setUserId(userId);
				vo.setRoleId(roleId);
				vo.setCreateId(createId);
				insertList.add(vo);
			}
			map.put(userId, userId);
		}
		// 如果存储的数据在传递的数据中没找到,删除
		for (Entry<Integer, UserRoleVO> entry : userRoleMap.entrySet()) {
			Integer userId = entry.getKey();
			UserRoleVO userRoleVO = entry.getValue();
			if (map.get(userId) == null) {
				deleteList.add(userRoleVO.getUserId());
			}
		}

		// 3)delete or insert
		if (CollectionUtils.isNotEmpty(deleteList)) {
			userRoleDao.deleteUserRoleByUserIdList(deleteList);
		}
		if (CollectionUtils.isNotEmpty(insertList)) {
			int N = GlobalConstant.DEFAULT_BATCH_SIZE;
			int size = insertList.size();
			int index = 0;
			int toIndex = N;
			while (toIndex < size) {
				userRoleDao.insertUserRoleList(insertList.subList(index, toIndex));
				toIndex += N;
				index += N;
			}
			userRoleDao.insertUserRoleList(insertList.subList(index, size));
		}
		return true;
	}

	/**
	 * 方法描述:是否是用户
	 *
	 * @param id
	 * @return
	 */
	private static boolean isUser(String id) {
		if (id.isEmpty()) {
			return false;
		}
		return id.charAt(0) == 'u';
	}

	@Override
	public List<TreeNodeVO<OrgTreeVO>> queryDeptOrgTreeList() {
		Map<String, Object> condition = new HashMap<String, Object>();
		List<OrgTreeVO> list = deptinfoDao.queryDeptOrgTreeList(condition);
		return TreeUtil.buildTree(list, null);
	}

	@Override
	public boolean addDeptinfo(DeptinfoVO deptinfo, UserVO user) {
		// 插入部门
		Integer count = deptinfoDao.insertDeptinfo(deptinfo);
		if (count > 0) {
			Integer createId = deptinfo.getCreateId();

			// 插入管理员角色
			RoleVO role = new RoleVO();
			role.setDeptId(deptinfo.getDeptId());
			String deptAdminName = getDeptAdminName(deptinfo.getDeptName());
			role.setRoleName(deptAdminName);
			role.setCreateId(createId);
			roleDao.insertRole(role);

			// 插入管理员用户
			user.setDeptid(deptinfo.getDeptId());
			user.setUsername(deptAdminName);
			user.setUstatus(1);
			userDao.insertUser(user);

			// 插入管理员用户与管理员角色的关联关系
			UserRoleVO userRole = new UserRoleVO();
			userRole.setUserId(user.getUserid());
			userRole.setRoleId(role.getRoleId());
			userRole.setCreateId(createId);
			userRoleDao.insertUserRole(userRole);

			// 修改部门的管理员角色id
			DeptinfoVO updateDept = new DeptinfoVO();
			updateDept.setDeptId(deptinfo.getDeptId());
			updateDept.setRoleId(role.getRoleId());
			deptinfoDao.updateDeptinfoRoleById(updateDept);
		}
		return count > 0;
	}

	/**
	 * 方法描述:根据部门名称生成部门管理员的名称
	 *
	 * @param deptName
	 * @return
	 */
	private static String getDeptAdminName(String deptName) {
		return deptName + "管理员";
	}

	/**
	 * 方法描述:获取部门的Id
	 *
	 * @return
	 */
	private static String getDeptId() {
		UserVO user = SessionInfoUtil.getSessionUserInfo();
		String deptId = null;
		if (!GlobalConstant.ADMIN_NAME.equalsIgnoreCase(user.getLoginname())) {
			Integer id = user.getDeptid();
			deptId = id.toString();
		}
		return deptId;
	}

	@Override
	public List<DeptinfoVO> queryDeptinfoById(Integer deptId) {
		DeptinfoVO deptinfo = new DeptinfoVO();
		deptinfo.setDeptId(deptId);
		return deptinfoDao.queryDeptinfo(deptinfo);
	}

}
